/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package suministros.ejb30.DAO;

import java.io.InputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.sql.DataSource;
import org.apache.commons.io.IOUtils;

import suministros.ejb30.entity.Empresa;

/**
 *
 * @author Luis_Angel
 */
@Stateless
public class SumiGestionEmpresaDAO implements SumiGestionEmpresaDAOLocal {

      @PersistenceUnit(unitName="suministros-pu")
      EntityManagerFactory emf;
      EntityManager em;

     @Resource(name="jdbc/Administracion")
      DataSource dsAdministracion;

     @PostConstruct
      public void inicializaBean()
      {
        this.em = this.emf.createEntityManager();
      }

    @PreDestroy
      public void finalizaBean() {
        this.em.close();
      }

    public boolean insertarEmpresa(Empresa emp) throws Exception {
        boolean retorno = false;
         EntityTransaction tx = this.em.getTransaction();
          tx.begin();
           try {
                if(emp.isIsPrincipal()){
                        Query q = this.em.createNamedQuery("Empresa.findAll");
                       List<Empresa> empresas = (List<Empresa>)q.getResultList();
                       for (Empresa empresa : empresas) {
                           empresa.setIsPrincipal(false);
                           this.em.merge(empresa);
                       }
                       
                 }
               emp.setIdEmpresa(getIdEmpresa());
               emp.setIsPrincipal(emp.isIsPrincipal());
               this.em.persist(emp);
               this.em.flush();
                tx.commit();
              retorno = true;
            } catch (Exception e) {
                 tx.rollback();
              throw e;
            }
           return retorno;
    }

     public boolean actualizarEmpresa(Empresa emp) throws Exception {
          boolean retorno = false;
         EntityTransaction tx = this.em.getTransaction();
          tx.begin();
           try {
                if(emp.isIsPrincipal()){
                        Query q = this.em.createNamedQuery("Empresa.findAll");
                       List<Empresa> empresas = (List<Empresa>)q.getResultList();
                       for (Empresa empresa : empresas) {
                           empresa.setIsPrincipal(false);
                           this.em.merge(empresa);
                       }

                 }
                Empresa emp_old = this.em.find(Empresa.class,emp.getIdEmpresa());
                emp_old.setRazonSocial(emp.getRazonSocial());
                emp_old.setRuc(emp.getRuc());
                emp_old.setDescDireccion(emp.getDescDireccion());
                emp_old.setLogo(emp.getLogo());
                emp_old.setIsPrincipal(emp.isIsPrincipal());
                this.em.merge(emp_old);
                this.em.flush();
                tx.commit();
              retorno = true;
            } catch (Exception e) {
                 tx.rollback();
              throw e;
            }
           return retorno;
     }

    public String getIdEmpresa() throws Exception {
         String retorno = null;
        Connection cnx = null;
        try {
          //Utiles_Fecha fecha = new Utiles_Fecha(orden.getFechaemision());
          cnx = this.dsAdministracion.getConnection();
          CallableStatement csLlamada = cnx.prepareCall("{? = call [dbo].[f_sumi_getcodigoEmpresa]()}");
          csLlamada.registerOutParameter(1, 12);
          csLlamada.execute();
          retorno = csLlamada.getString(1);
        }
        catch (SQLException ex) {
          throw ex;
        } finally {
          try {
            cnx.close();
          } catch (Exception ex) {
            ;
          }
        }
        return retorno;
    }

     public byte[] getLogoEmpresa(String id_empresa) throws Exception {
         byte[] data=null;
        Connection cnx = null;
        try {
          //Utiles_Fecha fecha = new Utiles_Fecha(orden.getFechaemision());
          cnx = this.dsAdministracion.getConnection();
          PreparedStatement csLlamada = cnx.prepareStatement("select logo from empresa where id_empresa='" +id_empresa+"'");
          ResultSet rs =csLlamada.executeQuery();

          while(rs.next()){
               InputStream is = rs.getBinaryStream(1);
               data = IOUtils.toByteArray(is);
              /* Filefile = new File(id_comprobante+".pdf");
               org.apache.commons.io.FileUtils.writeByteArrayToFile(file, data);*/
          }
        }
        catch (SQLException ex) {
          throw ex;
        } finally {
          try {
            cnx.close();
          } catch (Exception ex) {
            Logger.getLogger(SumiGestionPedidoDAO.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
       return data;

    }



    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
 
}
